package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.RolWindowData;
import com.ironman.common.params.RolParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class RolPostHandler extends BasePostHandler<RolWindowData> {

    private Double preRol = null;

    private final RolParam rolParam;

    public RolPostHandler(RolParam rolParam) {
        this.rolParam = rolParam;
    }

    @Override
    public void handler(RolWindowData data, Consumer<RolWindowData> consumer) {
        doHandler(data, consumer);
    }

    @Override
    public void threshold(RolWindowData data) {
        Double rol = data.getRol();
        if (Objects.isNull(rol)) {
            return;
        }

        if (preRol == null) {
            getCounter().incrementAndGet();
            preRol = rol;
            return;
        }


        Integer rolThreshold = rolParam.getRolThreshold();
        double diff = Math.abs(rol - preRol);
        if (diff > rolThreshold) {
            getCounter().set(0);
            log.debug("平衡触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", rolThreshold, rol, preRol, diff);
            preRol = rol;
            return;
        }

        Integer countThreshold = rolParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.debug("平衡触发数量阈值:{} ", countThreshold);
            preRol = rol;
            return;
        }
        data.setRol(preRol);
    }

}
